﻿using System;
using System.Collections.Generic;
using System.Text;
using ULTCONFIGURATIONLib;
using Portal.Interface;
using Portal.Entity;
using System.Data;
using MyLib;
using System.Web;
using System.Collections;

namespace Workflow.Logic
{
    public class GoodWindOrgLogic : UltimusOrgLogic
    {
        public override Portal.Entity.UserEntity GetUserEntity(string loginName)
        {
            if (HttpContext.Current.Session["UserEntity"] != null)
            {
                return HttpContext.Current.Session["UserEntity"] as Portal.Entity.UserEntity;
            }
            if (loginName == null || loginName.Trim() == "")
            {
                throw new Exception("你系统登录的时间过长,请关闭此页面并从门户重新登录。");
            }
            UserEntity ety = new UserEntity();
            Ultimus.OC.OrgChart oc = new Ultimus.OC.OrgChart();
            Ultimus.OC.User user = new Ultimus.OC.User();
            bool bflag = oc.FindUser(loginName.Replace("\\", "/"), "", 0, out user);
            ety.LoginName = loginName;
            if (!bflag || user.strUserFullName.ToLower() == loginName.Replace("\\", "/").ToLower())
            {
                string strSql = "select a.EmployeeID,a.FirstName,a.Title,c.DepartmentName from v_employee a  " +
                    " inner join v_empdepartments b on a.EmployeeID = b.EmployeeID " +
                    " inner join v_department c on c.DepartmentID = b.DepartmentID " +
                    " where a.ShortName='" + loginName.Replace("\\", "/") + "'";
                DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(strSql);
                if (dt.Rows.Count > 0)
                {
                    ety.CNName = ConvertUtil.ToString(dt.Rows[0][1]);
                    ety.ENName = ety.CNName;
                    ety.UserId = ConvertUtil.ToInt32(dt.Rows[0][0]);
                    ety.JobFunction = ConvertUtil.ToString(dt.Rows[0][2]);
                    ety.Ext01 = ConvertUtil.ToString(dt.Rows[0][3]);// ext01:当前部门名称
                }
            }
            else
            {

                ety.CNName = user.strUserFullName;
                ety.ENName = user.strUserFullName;
                ety.UserId = user.nUserID;
                ety.JobFunction = user.strJobFunction;

                ety.Ext01 = user.strDepartmentName; //ext01:当前部门名称
            }
            ety.Ext03 = "";
            Ultimus.OC.Department[] depts;
            user.GetUserDepartments(out depts);
            if (depts != null && depts.Length > 0)
            {
                //ety.Ext02 = Convert.ToInt32(depts[0].strDepartmentID).ToString(); //ext02:当前部门ID
                LogUtil.Info("Get DeptID Employeeid:" + ety.UserId.ToString());
                DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable("select * from V_EMPLOYEE v where v.EmployeeID=" + ety.UserId);

                //ety.Ext02 = dt.Rows[0]["DepartmentID"].ToString();

                //修改人：陈杰
                //修改日期：2013-11-21
                if (dt.Rows.Count > 0)
                {
                    ety.Ext02 = dt.Rows[0]["DepartmentID"].ToString();
                }
                else
                {
                    ety.Ext02 = "";
                }
            }
            else
            {
                DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable("select * from V_EMPLOYEE v where v.EmployeeID=" + ConvertUtil.ToString(ety.UserId));

                //ety.Ext02 = ConvertUtil.ToString(dt.Rows[0]["DepartmentID"]);

                //修改人：陈杰
                //修改日期：2013-11-21
                if (dt.Rows.Count > 0)
                {
                    ety.Ext02 = dt.Rows[0]["DepartmentID"].ToString();
                }
                else
                {
                    ety.Ext02 = "";
                }
            }
            //获取用户的一级部门信息
            DataTable firstLevel = GetFirstLevelDepartment();
            string deptId = ety.Ext02;
            while (true && !string.IsNullOrEmpty(deptId))
            {
                DataRow[] dr = firstLevel.Select("DepartmentID=" + deptId);
                if (dr.Length > 0)
                {
                    ety.Ext03 = ConvertUtil.ToString(dr[0]["DepartmentName"]);//ext03:一级部门名称
                    ety.Ext04 = ConvertUtil.ToString(dr[0]["DepartmentID"]);//ext04:一级部门ID
                    break;
                }
                else
                {
                    deptId = GetParentDepartmentId(deptId);
                    if (string.IsNullOrEmpty(deptId))
                    {
                        break;
                    }
                }
            }
            //todo:获取一级部门领导或者中心主任
            //ety.Ext05 = "ULTIMUS/1272";
            if (ety.Ext04 == null)
            {
                ety.Ext04 = "";
            }
            ety.Ext05 = GetDeptManager(ety.Ext04);

            //todo:获取上级主管
            //ety.Ext06 = "ULTIMUS/1273";
            ety.Ext06 = GetDeptManager(ety.Ext02);
            if (string.IsNullOrEmpty(ety.Ext06))
            {
                //直属上级找不到，那么找分管
                ety.Ext06 = GetFenGuanManager(ety.Ext02);
                if (string.IsNullOrEmpty(ety.Ext06))
                {
                    //分管找不到，那么一直往上找主管
                    string currentDeptID = ety.Ext02;
                    while (true)
                    {
                        string parentDeptId = GetParentDeparmentFromSAP(currentDeptID);
                        if (!string.IsNullOrEmpty(parentDeptId))
                        {
                            string parentManager = GetDeptManager(parentDeptId);
                            if (!string.IsNullOrEmpty(parentManager))
                            {
                                ety.Ext06 = parentManager;
                                break;
                            }
                            else
                            {
                                currentDeptID = parentDeptId;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            //todo:获取分管中心副主任     modify by Sky    2013-6-14 13:42
            //ety.Ext07 分管中心副主任
            ety.Ext07 = GetFenGuanManager(ety.Ext02);

            HttpContext.Current.Session["UserEntity"] = ety;
            return ety;
        }

        /// <summary>
        /// 获取部门领导
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        public string GetDeptManager(string deptId)
        {
            string deptAccount = "";
            string str = " select c.ShortName from v_zhr_relation_oa  a " +
                 "inner join v_zhr_relation_oa b on a.OBJID=b.SOBID and b.otype='P' and b.sclas='S' " +
                 "inner join v_employee c on to_number(b.OBJID)=c.EmployeeID " +
                 "where a.SOBID='{0}' and a.SUBTY='A012' and a.otype='S' and a.sclas='O'";
            str = string.Format(str, deptId.PadLeft(8, '0'));
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(str);
            if (dt.Rows.Count > 0)
            {
                deptAccount = ConvertUtil.ToString(dt.Rows[0][0]);
            }
            return deptAccount;
        }

        /// <summary>
        /// 获取分管领导
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        public string GetFenGuanManager(string deptId)
        {
            string deptAccount = "";
            string str = " select c.ShortName from v_zhr_relation_oa  a " +
                 "inner join v_zhr_relation_oa b on a.OBJID=b.SOBID and b.otype='P' and b.sclas='S' " +
                 "inner join v_employee c on to_number(b.OBJID)=c.EmployeeID " +
                 "where a.SOBID='{0}' and a.SUBTY='AZ05' and a.otype='S' and a.sclas='O'";
            str = string.Format(str, deptId.PadLeft(8, '0'));
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(str);
            if (dt.Rows.Count > 0)
            {
                deptAccount = ConvertUtil.ToString(dt.Rows[0][0]);
            }
            return deptAccount;
        }

        /// <summary>
        /// 获取部门经理
        /// </summary>
        /// <param name="deptId">部门Id</param>
        /// <param name="useFenGuan">是否启用分管</param>
        /// <param name="useSkip">是否启动跳过直管</param>
        /// <param name="directReport1">直接上级，一级领导</param>
        /// <param name="directReport2">二级领导</param>
        /// <param name="directReport3">三级领导</param>
        public void GetDepartmentManagers(string deptId, bool useFenGuan, bool useSkip, ref string directReport1, ref string directReport2, ref string directReport3)
        {
            Hashtable deptManagers = new Hashtable();
            string str = GetDeptManager(deptId);
            bool existManager = false;
            if (!string.IsNullOrEmpty(str))
            {
                existManager = true;
            }
            //1.启用分管关系，启用跳过(分管审，直管不审)，申请人部门存在部长。开发工程》信息部部长》张三》运营中心的上级部门主管（不经过运营副总监）
            if (existManager && useFenGuan && useSkip)
            {
                directReport1 = str;
                directReport2 = GetFenGuanManager(deptId);
                string pid = deptId;
                if (string.IsNullOrEmpty(directReport2))
                {
                    pid = GetParentDeparmentFromSAP(deptId.PadLeft(8, '0'));
                    directReport2 = GetDeptManagerOrParentManager(pid, ref pid);
                }
                directReport3 = GetDeptManager(GetParentDeparmentFromSAP(GetParentDeparmentFromSAP(deptId.PadLeft(8, '0'))));
            }
            //2.启用分管关系，不启用跳过(分管审，直管审)，申请人部门存在部长。开发工程师》信息部部长》张三》运营副总监》运营中心的上级部门主管
            if (existManager && useFenGuan && !useSkip)
            {
                directReport1 = str;
                directReport2 = GetFenGuanManager(deptId);
                string pid = deptId;
                if (string.IsNullOrEmpty(directReport2))
                {
                    pid = GetParentDeparmentFromSAP(deptId.PadLeft(8, '0'));
                    directReport2 = GetDeptManagerOrParentManager(pid, ref pid);
                }

                directReport3 = GetDeptManager(GetParentDeparmentFromSAP(deptId.PadLeft(8, '0')));
            }
            //3.启用分管关系，启用跳过(分管审，直管不审)，且假设此处不存在信息部部长 开发工程》张三》运营中心的上级部门主管（不经过运营副总监）
            if (!existManager && useFenGuan && useSkip)
            {
                directReport1 = GetFenGuanManager(deptId);
                string pid = deptId;
                if (string.IsNullOrEmpty(directReport1))
                {
                    deptId = GetParentDeparmentFromSAP(deptId.PadLeft(8, '0'));
                    directReport1 = GetDeptManagerOrParentManager(deptId, ref pid);
                }
                directReport2 = GetDeptManagerOrParentManager(pid, ref pid);
                directReport3 = GetDeptManagerOrParentManager(pid, ref pid);
            }
            //4.不启用分管。应用工程师》信息部部长》运营副总监
            if (!useFenGuan)
            {
                string pid = deptId;
                directReport1 = GetDeptManagerOrParentManager(pid, ref pid);
                directReport2 = GetDeptManagerOrParentManager(pid, ref pid);
                directReport3 = GetDeptManagerOrParentManager(pid, ref pid);
            }
            //directReport1 = "ULTIMUS/1272";
            //directReport2 = "ULTIMUS/1273";
            //directReport3 = "ULTIMUS/1274";
        }

        public string GetDeptManagerOrParentManager(string deptId, ref string parentDepartmentId)
        {
            string parentDeptId = "";
            while (true)
            {
                parentDeptId = GetParentDeparmentFromSAP(deptId.PadLeft(8, '0'));
                string deptManager = GetDeptManager(deptId);
                if (!string.IsNullOrEmpty(deptManager))
                {
                    parentDepartmentId = parentDeptId;
                    return deptManager;
                }
                if (string.IsNullOrEmpty(parentDeptId))
                {
                    break;
                }
                deptId = parentDeptId;
            }
            return "";
        }

        /// <summary>
        /// 获取上级部门ID
        /// </summary>
        /// <param name="deptID"></param>
        /// <returns></returns>
        public string GetParentDeparmentFromSAP(string deptID)
        {
            string parentDeptId = "";
            string str = "select sobid from v_zhr_relation_oa where objid='{0}' and otype='O' and SCLAS='O'";
            str = string.Format(str, deptID);
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(str);
            if (dt.Rows.Count > 0)
            {
                parentDeptId = ConvertUtil.ToString(dt.Rows[0][0]);
            }
            return parentDeptId;
        }

        public string GetParentDepartmentId(string deptId)
        {
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable("select ParentID from V_Department where DepartmentID=" + deptId);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0][0].ToString();
            }
            return "";
        }

        public DataTable GetFirstLevelDepartment()
        {
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable("select b.departmentid,b.DepartmentName from V_DEPARTMENT a inner join V_DEPARTMENT b on a.DepartmentID=b.ParentID  where a.parentid ='1000000'");
            return dt;
        }
    }
}
